package top.byfree.jbyan.saber.bean.dto

import cn.dev33.satoken.stp.StpUtil
import jakarta.validation.constraints.NotBlank
import jakarta.validation.constraints.Pattern
import jakarta.validation.constraints.Size
import top.byfree.jbyan.saber.bean.IS_DELETE_NO
import top.byfree.jbyan.saber.bean.Operate
import top.byfree.jbyan.saber.bean.ROLE_STATUS_NORMAL
import top.byfree.jbyan.saber.bean.pojo.Role
import top.byfree.jbyan.saber.bean.vo.UserVo
import top.byfree.jbyan.saber.common.AddGroup
import top.byfree.jbyan.saber.common.UpdateGroup
import java.time.LocalDateTime

/**
 * 角色dto
 *
 * @author jbyan
 * @since 26/3/2024
 */
data class RoleDto(

    /* 角色名称 */
    @field:NotBlank(message = "角色名称不能为空", groups = [AddGroup::class])
    @field:Size(
        min = 2,
        max = 8,
        message = "角色名称需要在2-8个字符之间",
        groups = [AddGroup::class, UpdateGroup::class]
    )
    var roleName: String?,

    /* 角色标识 */
    @field:NotBlank(message = "角色标识不能为空", groups = [AddGroup::class])
    @field:Pattern(
        regexp = "^[0-9_a-zA-Z]+\$",
        message = "角色标识只能包含字母数字和下划线",
        groups = [AddGroup::class, UpdateGroup::class]
    )
    var roleKey: String?,

    /* 状态 */
    @field:Pattern(
        regexp = "^([01])\$",
        message = "角色状态不符合码值规则",
        groups = [AddGroup::class, UpdateGroup::class]
    )
    var status: Int?,
) {
    fun toRole(cRoleId: String, type: Operate): Role {
        val userVo = (StpUtil.getSession().get("user") as? UserVo)!!
        val role = Role {
            roleId = cRoleId
            gmtModify = LocalDateTime.now()
            modifyBy = userVo.userId
        }

        roleName?.let {
            role.roleName = it
        }
        roleKey?.let {
            role.roleKey = it
        }

        role.status = status ?: ROLE_STATUS_NORMAL

        if (type == Operate.OPERATE_ADD) {
            role.gmtCreate = LocalDateTime.now()
            role.createBy = userVo.userId
            role.isDelete = IS_DELETE_NO
        }
        return role
    }
}